﻿/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2014 rocky, rockylin@qq.com
 *
 * 
 * NScheduler is free .NET library: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with NScheduler.  If not, see <http://www.gnu.org/licenses/>.
 *
 * NScheduler是一个自由.NET类库，您可以自由分发、修改其中的源代码或者重新发布它，
 * 新的任何修改后的重新发布版必须同样在遵守LGPL3或更后续的版本协议下发布.
 * 关于LGPL协议的细则请参考COPYING、COPYING.LESSER文件，
 * 您可以在NScheduler的相关目录中获得LGPL协议的副本，
 * 如果没有找到，请连接到 http://www.gnu.org/licenses/ 查看。
 *
 * - Author: Rocky Lin
 * - Contact: rockylin@qq.com
 * - License: GNU Lesser General Public License (LGPL)
 * - Blog and source code availability: https://lightso.codeplex.com/
 */
  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using System.Threading.Tasks;
using System.Threading;
using NScheduler;

namespace NScheduler
{
    /// <summary>
    /// 任务基类
    /// （派生的任务须重写Main方法，并且需要在构造方法中调用Enqueue才回进入Main方法，如：base.Queue.Enqueue("testtt")）
    /// </summary>
    /// <typeparam name="T">传入参数的类型</typeparam>
    /// <example>
    ///public class ExampleTask : TaskBase&lt;string&gt;
    ///{
    ///    public ExampleTask()
    ///    {
    ///        base.Queue.Enqueue("testtt");
    ///    }
    ///    public override void Main(object args)
    ///    {
    ///        Console.WriteLine(args);
    ///    }
    ///}
    /// </example>
    public abstract class TaskBase<T> : ITask
    {
        const string NAMESPACE = "NScheduler";
        static TaskBase()
        {
            _queue = new NSQueue<T>();
            var type = Type.GetType(string.Format("{0}.TaskSchedulerBase`1", NAMESPACE)).MakeGenericType(Config.SchedulerType);
            var instance = Activator.CreateInstance(type);
            _factory = (TaskFactory)Activator.CreateInstance(typeof(TaskFactory), instance);
        }

        private static TaskFactory _factory { get; set; }
        private static NSQueue<T> _queue { get; set; }
        protected NSQueue<T> Queue
        {
            get
            {
                return _queue;
            }
        }

        void ITask.Action()
        {
            if (Queue.Count < 1)
                return;

            foreach (var i in Queue)
            {
                _factory.StartNew((s) =>
                {
                    Main(s);

                }, i);
            }
            Queue.Clear();
        }

        /// <summary>
        /// 任务入口
        /// </summary>
        /// <param name="args"></param>
        public virtual void Main(object args) { }

        /// <summary>
        /// 获取当前队列数量
        /// </summary>
        /// <returns>返回当前队列数量</returns>
        int ITask.GetQuqueCount()
        {
            return Queue.Count;
        }

        /// <summary>
        /// IConfigurationSectionHandler接口实现
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="configContext"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        object System.Configuration.IConfigurationSectionHandler.Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            try
            {
                // Creates the configuration object that this method will return.
                // This can be a custom configuration class.
                // In this example, we use a System.Collections.Hashtable.
                Hashtable myConfigObject = new Hashtable();

                // Gets any attributes for this section element.
                Hashtable myAttribs = new Hashtable();
                foreach (XmlAttribute attrib in section.Attributes)
                {
                    if (XmlNodeType.Attribute == attrib.NodeType)
                        myAttribs.Add(attrib.Name, attrib.Value);
                }

                // Puts the section name and attributes as the first config object item.
                myConfigObject.Add(section.Name, myAttribs);

                // Gets the child element names and attributes.
                foreach (XmlNode child in section.ChildNodes)
                {
                    if (XmlNodeType.Element == child.NodeType)
                    {
                        Hashtable myChildAttribs = new Hashtable();

                        foreach (XmlAttribute childAttrib in child.Attributes)
                        {
                            if (XmlNodeType.Attribute == childAttrib.NodeType)
                                myChildAttribs.Add(childAttrib.Name, childAttrib.Value);
                        }
                        myConfigObject.Add(child.Name, myChildAttribs);
                    }
                }

                return (myConfigObject);
            }
            catch
            {
                return null;
            }
        }

        void IDisposable.Dispose()
        {
            
        }
    }
}
